package com.aaa.vegetablemarketexpress.shiro;

import com.aaa.vegetablemarketexpress.entity.Role;
import com.aaa.vegetablemarketexpress.entity.User;
import com.aaa.vegetablemarketexpress.service.MenuService;
import com.aaa.vegetablemarketexpress.service.RoleService;
import com.aaa.vegetablemarketexpress.service.UserService;
import com.aaa.vegetablemarketexpress.vo.TreeNode;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @FileName: MyCustomRealm
 * @Description:编写realm 是shiro和安全数据的桥梁
 *  *               必须遵循shiro规范extends
 * @Author: qxh
 * @CreateTime: 2025/9/26 16:12
 * @Version: 1.0.0
 */
public class MyCustomRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private MenuService menuService;
    /**
     * 执行获取授权信息 （角色和权限）
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户信息
        User user = (User) principalCollection.getPrimaryPrincipal();
        Long userId = user.getUserId();
        //根据用户编号获取角色列表
        List<Role> roleList = roleService.queryByUserId(userId);
        //根据用户编号获取权限列表
        List<TreeNode> menuList = menuService.queryAllMenuByUserId(userId);
        //实例化返回对象
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //判断角色列表是否为空
        if(!CollectionUtils.isEmpty(roleList)){
            //遍历
            for (Role role : roleList) {
                System.out.println("当前登录用户拥有的角色名称为："+role.getRoleName());
                //把当前登录用户的拥有所有角色名字，放入到授权信息中
                //simpleAuthorizationInfo.addStringPermission(role.getRoleName());
                simpleAuthorizationInfo.addRole(role.getRoleKey());//添加角色

            }
            //判断权限列表是否为空
            if(!CollectionUtils.isEmpty(menuList)){
                for (TreeNode menu : menuList) {
                    System.out.println("当前登录用户拥有的权限名称为："+menu.getLabel());
                    //把当前登录用户的拥有所有权限名字，放入到授权信息中
                    simpleAuthorizationInfo.addStringPermission(menu.getLabel());
                    //simpleAuthorizationInfo.addStringPermission(menu.getPerms());
                }
            }
        }
        return simpleAuthorizationInfo;//返回授权信息
    }
    /**
     * 执行获取认证信息 （用户信息）
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取当前登录用户的用户名
        String userName = authenticationToken.getPrincipal().toString();
        //根据用户名查询用户信息
        User user = userService.queryByUsername(userName);
        //判断用户是否存在
        if(user == null){
            //抛出(账号（用户名）)不存在的异常
            throw new AccountException("用户不存在");
        }
        //获取加密密码
        String password = user.getPassword();
        //获取盐
        String salt = user.getSalt();
        return new SimpleAuthenticationInfo(user,password, ByteSource.Util.bytes(salt),this.getName());
    }
    @Override
    public String getName() {
        return "myCustomRealm";
    }
}
